import 'package:flutter/material.dart';

class PathDrawingCanvas extends StatefulWidget {
  final Function(List<Offset>) onPathUpdated;
  final bool enabled;

  const PathDrawingCanvas({
    super.key,
    required this.onPathUpdated,
    this.enabled = true,
  });

  @override
  State<PathDrawingCanvas> createState() => _PathDrawingCanvasState();
}

class _PathDrawingCanvasState extends State<PathDrawingCanvas> {
  final List<Offset> _points = [];
  bool _isDrawing = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 背景网格
        CustomPaint(
          painter: GridPainter(),
          size: Size.infinite,
        ),
        // 绘制路径
        GestureDetector(
          onPanStart: widget.enabled ? _onPanStart : null,
          onPanUpdate: widget.enabled ? _onPanUpdate : null,
          onPanEnd: widget.enabled ? _onPanEnd : null,
          child: CustomPaint(
            painter: PathPainter(
              points: _points,
              isDrawing: _isDrawing,
              theme: Theme.of(context),
            ),
            size: Size.infinite,
          ),
        ),
        // 禁用状态覆盖层
        if (!widget.enabled)
          Container(
            color: Colors.black.withOpacity(0.1),
            child: const Center(
              child: Text(
                '飞行中无法编辑路径',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
      ],
    );
  }

  void _onPanStart(DragStartDetails details) {
    final RenderBox box = context.findRenderObject() as RenderBox;
    final point = box.globalToLocal(details.globalPosition);
    
    setState(() {
      _points.clear();
      _points.add(point);
      _isDrawing = true;
    });
    
    widget.onPathUpdated(_points);
  }

  void _onPanUpdate(DragUpdateDetails details) {
    if (!_isDrawing) return;
    
    final RenderBox box = context.findRenderObject() as RenderBox;
    final point = box.globalToLocal(details.globalPosition);
    
    // 只有当新点与最后一个点的距离超过一定阈值时才添加
    if (_points.isNotEmpty) {
      final lastPoint = _points.last;
      final distance = (point - lastPoint).distance;
      
      if (distance < 10) {
        return;
      }
    }
    
    setState(() {
      _points.add(point);
    });
    
    widget.onPathUpdated(_points);
  }

  void _onPanEnd(DragEndDetails details) {
    setState(() {
      _isDrawing = false;
    });
    
    widget.onPathUpdated(_points);
  }
}

class GridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.grey.withOpacity(0.2)
      ..strokeWidth = 1.0;

    // 绘制水平线
    for (double y = 0; y < size.height; y += 20) {
      canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
    }

    // 绘制垂直线
    for (double x = 0; x < size.width; x += 20) {
      canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
    }
  }

  @override
  bool shouldRepaint(GridPainter oldDelegate) => false;
}

class PathPainter extends CustomPainter {
  final List<Offset> points;
  final bool isDrawing;
  final ThemeData theme;

  PathPainter({
    required this.points,
    required this.isDrawing,
    required this.theme,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (points.isEmpty) return;

    // 绘制路径
    final pathPaint = Paint()
      ..color = theme.colorScheme.primary
      ..strokeWidth = 3.0
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..style = PaintingStyle.stroke;

    final path = Path();
    path.moveTo(points.first.dx, points.first.dy);
    
    for (int i = 1; i < points.length; i++) {
      path.lineTo(points[i].dx, points[i].dy);
    }
    
    canvas.drawPath(path, pathPaint);

    // 绘制起点
    final startPointPaint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.fill;
    
    canvas.drawCircle(points.first, 8, startPointPaint);
    
    // 绘制终点
    if (points.length > 1 && !isDrawing) {
      final endPointPaint = Paint()
        ..color = Colors.red
        ..style = PaintingStyle.fill;
      
      canvas.drawCircle(points.last, 8, endPointPaint);
    }

    // 绘制路径点
    final pointPaint = Paint()
      ..color = theme.colorScheme.secondary
      ..style = PaintingStyle.fill;
    
    for (int i = 1; i < points.length - 1; i++) {
      canvas.drawCircle(points[i], 4, pointPaint);
    }

    // 绘制方向箭头
    final arrowPaint = Paint()
      ..color = theme.colorScheme.primary
      ..style = PaintingStyle.fill;
    
    for (int i = 0; i < points.length - 1; i += 5) {
      if (i + 1 < points.length) {
        _drawArrow(canvas, points[i], points[i + 1], arrowPaint);
      }
    }
  }

  void _drawArrow(Canvas canvas, Offset start, Offset end, Paint paint) {
    final direction = end - start;
    final distance = direction.distance;
    final normalizedDirection = Offset(
      direction.dx / distance,
      direction.dy / distance,
    );
    final arrowSize = 10.0;
    
    final arrowPoint1 = end - Offset(
      normalizedDirection.dx * arrowSize,
      normalizedDirection.dy * arrowSize,
    ) + Offset(
      -normalizedDirection.dy * arrowSize / 2,
      normalizedDirection.dx * arrowSize / 2,
    );
    
    final arrowPoint2 = end - Offset(
      normalizedDirection.dx * arrowSize,
      normalizedDirection.dy * arrowSize,
    ) + Offset(
      normalizedDirection.dy * arrowSize / 2,
      -normalizedDirection.dx * arrowSize / 2,
    );
    
    final arrowPath = Path()
      ..moveTo(end.dx, end.dy)
      ..lineTo(arrowPoint1.dx, arrowPoint1.dy)
      ..lineTo(arrowPoint2.dx, arrowPoint2.dy)
      ..close();
    
    canvas.drawPath(arrowPath, paint);
  }

  @override
  bool shouldRepaint(PathPainter oldDelegate) {
    return points != oldDelegate.points || isDrawing != oldDelegate.isDrawing;
  }
} 